package jdbc;
//import com.mysql.cj.jdbc.Driver;

import java.sql.*;

/**
 * @author oldliu
 * @since 1.0
 */
public class HelloJdbc {
    public static void main(String[] args) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return;
        }
        //          固定：类型://ip+端口/数据库名?其他参数
        String url = "jdbc:mysql://localhost:3308/java82";
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        try {
            conn = DriverManager.getConnection(url, "root", "root1234");
            st = conn.createStatement();
            rs = st.executeQuery("select id,subjectname,classhour,gradeid from s_subject order by id desc limit 15");
            //获得接口实现类，一般是厂商的实现类
            System.out.println(conn.getClass().getName());
            System.out.println(st.getClass().getName());
            System.out.println(rs.getClass().getName());
            while (rs.next()) {
                long id = rs.getLong("id");
                String subjectname = rs.getString("subjectname");
                int hour = rs.getInt(3);//从1开始，第三列
                long gradeid = rs.getLong("gradeid");
                System.out.printf("id=%d,课程名=%s,学时：%d,年级号:%d\n", id, subjectname, hour, gradeid);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭最后处理，防止因异常产生，链接不会被关闭
            try {
                if (rs != null)
                    rs.close();

            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (st != null)
                    st.close();


            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (conn != null)
                    conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}
